package ParallelMachineArrangeImpl;

import java.util.ArrayList;

//3.1 时间表长度问题（不可中断）-LPS算法 (largest processing time first)
public class _3_1_1_LPS extends ParallelMachineArrange{

    @Override
    public void solve() {
        if(process==null) process = new int[]{5,5,4,4,3,3,3};
        artifacts = new ArrayList<>();
        processing_artifacts = new ArrayList<>();
        removed_artifacts = new ArrayList<>();
        for (int p : process) {
            Artifact a = new Artifact();
            a.process = p;a.remain_process = p;
            artifacts.add(a);
        }
        artifacts.sort((o1, o2) -> o2.process - o1.process);
        System.out.println(artifacts);
        int t;
        for(t=0;!isComplete();t++){
            System.out.printf("当前时间 t = %d\n",t);
            //当前有平行机空闲，向空闲机器添加工件
            if(processing_artifacts.size() < machines){
                int need = machines - processing_artifacts.size();
                for (int i = 0; i < need; i++) {
                    //防止数组越界
                    if(i< artifacts.size()){
                        Artifact e = artifacts.get(i);
                        //防止重复添加
                        if(!e.isActive) {
                            e.isActive = true;
                            processing_artifacts.add(e);
                        }
                    }
                }
            }
            //加工处理
            for (int i = 0; i < processing_artifacts.size(); i++) {
                Artifact artifact = processing_artifacts.get(i);
                //加工会减少工件的剩余处理时间
                if(!artifact.isComplete) {
                    artifact.remain_process--;
                    System.out.printf("平行机 %d 正在加工工件 %s 剩余时间 %d\n", (i + 1), artifact, artifact.remain_process);
                }
                //有工件完工，标记（立刻移除会导致平行机标号混乱）
                if(artifact.remain_process<=0) {
                    artifact.isComplete = true;
                }
            }
            //将已完工的工件从现有的工件列表和平行机移除，方便下次循环处理数据
            for (int i = 0; i < processing_artifacts.size(); i++) {
                Artifact artifact = processing_artifacts.get(i);
                if(artifact.isComplete){
                    processing_artifacts.remove(i);
                    i--;
                }
            }
            for (int i = 0; i < artifacts.size(); i++) {
                Artifact artifact = artifacts.get(i);
                if(artifact.isComplete){
                    removed_artifacts.add(artifacts.remove(i));
                    i--;
                }
            }
        }
        System.out.println("已完工，用时：" + t);
    }
}
